package com.beauty.controller;

import com.beauty.dto.BeautyResponse;
import com.beauty.dto.note.User;
import com.beauty.dto.user.ChangeAvatarData;
import com.beauty.mapper.IUserMapper;
import com.beauty.services.MyBaitsHelp;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/user")
public class UserController {
    private final MyBaitsHelp myBaitsHelp;

    UserController(MyBaitsHelp myBaitsHelp) {
        this.myBaitsHelp = myBaitsHelp;
    }

    /**
     * 获得用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfo")
    public BeautyResponse<User> getUserInfo(@RequestParam(defaultValue = "") String userId, @CookieValue(name = "userId", defaultValue = "") String cookieUserId) {
        var res = new BeautyResponse<User>();
        res.response = new User();
        // 开始操作数据库
        try (var session = this.myBaitsHelp.factory.openSession()) {
            var user = new com.beauty.models.User();
            if (!userId.isEmpty()) {
                user = session.getMapper(IUserMapper.class).selectUserById(userId);
            } else if (cookieUserId != null) {
                user = session.getMapper(IUserMapper.class).selectUserById(cookieUserId);
            }
            res.response.id = user.id;
            res.response.name = user.name;
            res.response.avatar = user.avatar;
            return res;
        } catch (Error e) {
            res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
            return res;
        }
    }

    /**
     * 换头像
     *
     * @param userId
     * @param avatar
     * @return
     */
    @PostMapping("/changeAvatar")
    public BeautyResponse<String> changeAvatar(@RequestBody() ChangeAvatarData changeData) {
        var res = new BeautyResponse<String>();
        // 开始操作数据库
        try (var session = this.myBaitsHelp.factory.openSession()) {
            session.getMapper(IUserMapper.class).UpdateAvatar(changeData.userId, changeData.avatar);
            res.message = "更新成功";
            return res;
        } catch (Error e) {
            res.message = e.getMessage();
            return res;
        }
    }


}
